//
//  DDQuestionsLibViewController.m
//  dingdang
//
//  Created by Chen Jing on 15-7-6.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDQuestionsLibViewController.h"
#import "DDQuestionsLibCollectionViewCell.h"
#import "ModelQuestionList.h"
#import "DDNetWorkAPIClient.h"
#import "DDTempFlag.h"
#import "MJRefresh.h"
#import "DateUtil.h"
#import "UIImageView+WebCache.h"
#import "DDTypeDefine.h"
#import "DDQuestionBaseInfoViewController.h"

@interface DDQuestionsLibViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIPickerViewDataSource,UIPickerViewDelegate,UIActionSheetDelegate>{
    BOOL flag_isChooseAll;
    NSMutableArray * array_flag_choosed;
    NSMutableArray * array_show;
    ModelQuestionList * hold_model;
    DDNetWorkAPIClient * client;
    NSInteger pageIndex;
    NSInteger choosedNumber_integer;

    CGRect holdRect_contentOfChooseView;
    BOOL flagShow_contentOfChoose;

    NSMutableArray * array_question_type;
    NSMutableArray * array_question_libType;

    NSString * choosedQuestionType;
    NSString * choosedQuestionLibType;
}

@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView_chooseAllFlag;
@property (weak, nonatomic) IBOutlet UILabel *label_choosedNumber;
@property (weak, nonatomic) IBOutlet UIButton *btn_nextStep;
@property (weak, nonatomic) IBOutlet UIView *contentOfChooseView;
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UIView *contentOfMain;

@end

@implementation DDQuestionsLibViewController

- (void)viewDidLoad {
    NSLog(@"进入到---------->DDQuestionsLibViewController");
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.


    [self createUI];
    [self createData];
}

-(void)createUI{
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self addNavigatorTitle:NSLocalizedString(@"题库出题", nil) parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];
    [self AddLeftBtnAction:@"" normal:@"top_返回" selected:@"top_返回" action:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];

    
    [self.myCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([DDQuestionsLibCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([DDQuestionsLibCollectionViewCell class])];

    self.myCollectionView.headerPullToRefreshText = @"下拉可以刷新了";
    self.myCollectionView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.myCollectionView.headerRefreshingText = @"别再拉了,裤子要被拉下来了...";

    self.myCollectionView.footerPullToRefreshText = @"上提可以刷新了";
    self.myCollectionView.footerReleaseToRefreshText = @"松开马上刷新了";
    self.myCollectionView.footerRefreshingText = @"别再拉了,裤子要被拉下来了...";


    [self.myCollectionView addHeaderWithCallback:^{
        [self getDataFromServer_refrash];
    }];

    [self.myCollectionView addFooterWithCallback:^{
        [self getDataFromServer_more];
    }];

}

-(void)createData{
    array_flag_choosed = [NSMutableArray array];
    array_show = [NSMutableArray array];

    array_question_type = [NSMutableArray array];
    array_question_libType = [NSMutableArray array];

    [array_question_type addObject:@"题目类型"];
    [array_question_type addObjectsFromArray:QuestionTypeArray];

    [array_question_libType addObjectsFromArray:@[@"题库类型",@"已发布",@"未发布"]];

    pageIndex = 0;
    choosedNumber_integer = 0;
    client = [[DDNetWorkAPIClient alloc]init];
    flagShow_contentOfChoose = NO;

    [self.myCollectionView headerBeginRefreshing];
}

-(void)getDataFromServer_refrash{
    pageIndex = 0;

    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:@{@"pageIndex" : [NSNumber numberWithInteger:pageIndex]}];
    if (![choosedQuestionType isEqualToString:@"题目类型"] && choosedQuestionType && [QuestionTypeDic objectForKey:choosedQuestionType]) {
        [param setObject:[NSNumber numberWithInteger:[[QuestionTypeDic objectForKey:choosedQuestionType] integerValue]] forKey:@"type"];
    }
    if ([choosedQuestionLibType isEqualToString:@"已发布"]) {
        [param setObject:[NSNumber numberWithBool:YES] forKey:@"publiced"];
    }else if([choosedQuestionLibType isEqualToString:@"未发布"]){
        [param setObject:[NSNumber numberWithBool:NO] forKey:@"publiced"];
    }


    [client mainQuestionList:param completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        hold_model = (ModelQuestionList *)object;
        if (hold_model.info_total.integerValue > 0) {
            [array_show removeAllObjects];
            [array_flag_choosed removeAllObjects];

            [array_show addObjectsFromArray:hold_model.info_list];
            


            for (int i = 0 ; i < array_show.count; i++) {
                DDTempFlag * flag = [[DDTempFlag alloc]init];
                [flag resetFlagValueWithNO];
                [array_flag_choosed addObject:flag];
            }

            [self.myCollectionView reloadData];
        }
        [self.myCollectionView headerEndRefreshing];
    }];
}

-(void)getDataFromServer_more{
    if (array_show.count < hold_model.info_total.integerValue) {
        pageIndex++;
        NSDictionary * param = @{@"pageIndex" : [NSNumber numberWithInteger:pageIndex]};
        [client mainQuestionList:param completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
            ModelQuestionList * tempModel = (ModelQuestionList *)object;
            [hold_model.info_list addObjectsFromArray:tempModel.info_list];
            if (hold_model.info_total.integerValue > 0) {
                [array_show addObjectsFromArray:tempModel.info_list];

                for (int i = 0 ; i < tempModel.info_list.count; i++) {
                    DDTempFlag * flag = [[DDTempFlag alloc]init];
                    [flag resetFlagValueWithNO];
                    [array_flag_choosed addObject:flag];
                }

                [self.myCollectionView reloadData];
            }
            [self.myCollectionView footerEndRefreshing];
        }];
    }else{
        [self delayHUD:@"已全部加载完成..."];
        [self.myCollectionView footerEndRefreshing];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return array_show.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    DDQuestionsLibCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([DDQuestionsLibCollectionViewCell class]) forIndexPath:indexPath];

    DDTempFlag * flag = [array_flag_choosed objectAtIndex:indexPath.row];
    if (flag.info_flag == YES) {
        cell.imageView_chooseFlag.image = [UIImage imageNamed:@"发问-出题库-选择框-选中"];
    }else{
        cell.imageView_chooseFlag.image = [UIImage imageNamed:@"发问-出题库-选择框-未选中"];
    }

    ModelQuestionListElement * model = array_show[indexPath.row];
    NSRange timeRange;
    timeRange.location = 0;
    timeRange.length = 10;
    NSTimeInterval createTime = [[model.info_createTime substringWithRange:timeRange] integerValue];
    NSDate * myDate = [NSDate dateWithTimeIntervalSince1970:createTime];
    cell.label_time.text = [DateUtil format:@"YYYY-MM-dd HH:mm" date:myDate];
    cell.label_body.text = @"";
    cell.imageView_body.image = nil;
    for (ModelQuestionListElement_optionsOrExplanation_content * element in model.info_body) {
        if ([element.info_type isEqualToString:@"TEXT"]){
            cell.label_body.text = element.info_text;
        }
        if ([element.info_type isEqualToString:@"IMAGE"]) {
            [cell.imageView_body sd_setImageWithURL:[NSURL URLWithString:element.info_url] placeholderImage:[UIImage imageNamed:@"首页-答疑-客观题-单选习题拍照图-通用"]];
        }

    }
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    DDQuestionsLibCollectionViewCell * cell = (DDQuestionsLibCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    DDTempFlag * flag = [array_flag_choosed objectAtIndex:indexPath.row];
    flag.info_flag = !flag.info_flag;
    if (flag.info_flag == NO) {
        if (choosedNumber_integer == array_flag_choosed.count) {
            self.imageView_chooseAllFlag.image = [UIImage imageNamed:@"发问-出题库-选择框-未选中"];
            flag_isChooseAll = NO;
        }
        choosedNumber_integer--;

    }else{
        choosedNumber_integer++;
        if (choosedNumber_integer == array_flag_choosed.count) {
            self.imageView_chooseAllFlag.image = [UIImage imageNamed:@"发问-出题库-选择框-选中"];
            flag_isChooseAll = YES;
        }
    }

    NSNumber * choosedNumber = [NSNumber numberWithInteger:choosedNumber_integer];
    self.label_choosedNumber.text = [NSString stringWithFormat:@"已选%@题",choosedNumber];

    [collectionView reloadItemsAtIndexPaths:@[indexPath]];

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    ModelQuestionListElement * model = array_show[indexPath.row];
    CGSize tempSize;
    tempSize.width = self.view.frame.size.width - 16;
    tempSize.height = 70;
    for (ModelQuestionListElement_optionsOrExplanation_content * element in model.info_body) {
        if ([element.info_type isEqualToString:@"IMAGE"]) {
            tempSize.height = 160;
        }
    }
    return tempSize;
}
- (IBAction)btnChooseQuestionType:(id)sender {
    [self showContentOfChooseView];
}
- (IBAction)btnChooseQuestionLibType:(id)sender {
    [self showContentOfChooseView];
}

- (IBAction)btnNextStepClick:(id)sender {
    if (choosedNumber_integer > 1) {
        UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle:@"请选择分类" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"加密",@"悬赏", nil];
        [actionSheet showInView:self.view];
    }else if (choosedNumber_integer == 1){
        UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle:@"请选择分类" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"加密",@"悬赏",@"晒晒", nil];
        [actionSheet showInView:self.view];
    }else{
        [self delayHUD:@"请选择题目"];
    }
}

- (IBAction)btnChooseAllOrCancelClick:(id)sender {
    flag_isChooseAll = !flag_isChooseAll;
    [self fixTheChooseStatus];
}
- (IBAction)btnChooseTypeCancel:(id)sender {
    [self hiddenContentOfChooseView];
}
- (IBAction)btnChooseTypeCommit:(id)sender {
    [self hiddenContentOfChooseView];

    choosedQuestionType = [array_question_type objectAtIndex:[self.pickerView selectedRowInComponent:0]];
    choosedQuestionLibType = [array_question_libType objectAtIndex:[self.pickerView selectedRowInComponent:1]];

    [self.myCollectionView headerBeginRefreshing];
}

-(void)showContentOfChooseView{
    if (holdRect_contentOfChooseView.origin.y == 0) {
        holdRect_contentOfChooseView = self.contentOfChooseView.frame;
    }

    if (flagShow_contentOfChoose == NO) {
        flagShow_contentOfChoose = YES;
        [UIView animateWithDuration:.35 animations:^{
            self.contentOfChooseView.frame = CGRectMake(0,
                                                        self.contentOfMain.frame.size.height - self.contentOfChooseView.frame.size.height,
                                                        self.contentOfChooseView.frame.size.width,
                                                        self.contentOfChooseView.frame.size.height);
        }];
    }


}

-(void)hiddenContentOfChooseView{
    if (flagShow_contentOfChoose == YES) {
        flagShow_contentOfChoose = NO;
        [UIView animateWithDuration:.35 animations:^{
            self.contentOfChooseView.frame = holdRect_contentOfChooseView;
        }];
    }

}


-(void)fixTheChooseStatus{
    if (flag_isChooseAll) {
        self.imageView_chooseAllFlag.image = [UIImage imageNamed:@"发问-出题库-选择框-选中"];
        for (DDTempFlag * flag in array_flag_choosed) {
            flag.info_flag = YES;
        }
        choosedNumber_integer = array_flag_choosed.count;
        NSNumber * choosedNumber = [NSNumber numberWithInteger:choosedNumber_integer];
        self.label_choosedNumber.text = [NSString stringWithFormat:@"已选%@题",choosedNumber];
        [self.myCollectionView reloadData];
    }else{
        self.imageView_chooseAllFlag.image = [UIImage imageNamed:@"发问-出题库-选择框-未选中"];
        for (DDTempFlag * flag in array_flag_choosed) {
            flag.info_flag = NO;
        }
        choosedNumber_integer = 0;
        self.label_choosedNumber.text = [NSString stringWithFormat:@"已选0题"];

        [self.myCollectionView reloadData];
    }
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return array_question_type.count;
    }else{
        return array_question_libType.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component == 0) {
        return array_question_type[row];
    }else{
        return array_question_libType[row];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    NSMutableArray * tempArray = [NSMutableArray array];
    for (int i = 0; i < array_flag_choosed.count; i++) {
        DDTempFlag * flag = array_flag_choosed[i];
        if (flag.info_flag == YES) {
            ModelQuestionListElement * element = array_show[i];
            [tempArray addObject:[NSNumber numberWithLong:element.info_id.integerValue]];
        }
    }

    if (buttonIndex == 0) {
        //加密
        DDQuestionBaseInfoViewController * baseInfo = [[DDQuestionBaseInfoViewController alloc]init];
        baseInfo.info_questions = tempArray;
        baseInfo.info_publishType = DDType_question_questionPublishType_Encryption;
        [self.navigationController pushViewController:baseInfo animated:YES];

    }else if (buttonIndex == 1){
        //悬赏
        DDQuestionBaseInfoViewController * baseInfo = [[DDQuestionBaseInfoViewController alloc]init];
        baseInfo.info_questions = tempArray;
        baseInfo.info_publishType = DDType_question_questionPublishType_Reward;
        [self.navigationController pushViewController:baseInfo animated:YES];

    }else if (buttonIndex == 2){
        if (actionSheet.numberOfButtons == 4) {
            //晒晒（原大家帮）
            DDQuestionBaseInfoViewController * baseInfo = [[DDQuestionBaseInfoViewController alloc]init];
            baseInfo.info_questions = tempArray;
            baseInfo.info_publishType = DDType_question_questionPublishType_help;
            [self.navigationController pushViewController:baseInfo animated:YES];
        }

    }

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
